package com.caifu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.Result;
import com.caifu.mapper.SysOrganizationMapper;
import com.caifu.mapper.SysRecordMapper;
import com.caifu.mapper.SysUserMapper;
import com.caifu.pojo.SysOrganization;
import com.caifu.pojo.SysUser;
import com.caifu.util.AesUtil;
import com.caifu.util.CheckUtil;
import com.caifu.util.Util;
import com.caifu.vo.RecordVO;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author szt
 * ClassName: SysRecordService.java、
 * createTime: 2021年03月09日 14:47:32
 **/
@Service
public class SysRecordService {

    @Resource
    private SysRecordMapper recordMapper;
    @Resource
    private SysOrganizationMapper organizationMapper;

    public JSONObject pageRecord(RecordVO vo, Integer currentPage, Integer pageSize) throws Exception {
        JSONObject obj = new JSONObject();
        long page=(currentPage-1)*pageSize;
        if(StringUtils.isNotBlank(vo.getStartDay())){
            vo.setStartDay(vo.getStartDay()+"000000");
        }
        if(StringUtils.isNotBlank(vo.getEndDay())){
            vo.setEndDay(vo.getEndDay()+"235959");
        }
        List<Map<String,Object>> list = recordMapper.pageRecord(page,pageSize,vo.getUserName(),vo.getStartDay(), vo.getEndDay());
        list.forEach(tmpObj->{
            String orgId = (String) tmpObj.get("org_id");
            tmpObj.put("org_id",getOrgAncestors(orgId));
        });
        Long count = recordMapper.totalRecord(vo.getUserName(),vo.getStartDay(), vo.getEndDay());
        obj.put("data",list);
        obj.put("curPage",currentPage);
        obj.put("pageSize",pageSize);
        obj.put("count",count);
        obj.put("code",0);
        return obj;
    }

    private String getOrgAncestors(String id){
        SysOrganization org = organizationMapper.selectById(id);
        String name="";
        if(org!=null){
            String[] arr = org.getAncestors().split(",");

            for (int i = 1; i < arr.length; i++) {
                SysOrganization tmpOrg = organizationMapper.selectById(Integer.parseInt(arr[i]));
                if(i==1){
                    name+=tmpOrg.getName();
                }else{
                    name+=">"+tmpOrg.getName();
                }

            }

        }
        return name;
    }

}
